package com.pz.gulimall.member.exception;

import com.pz.gulimall.common.exception.BizCodeEnum;
import com.pz.gulimall.common.exception.RRException;
import com.pz.gulimall.common.utils.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * 集中处理所有的异常，配合数据校验优化代码
 */
@Slf4j
@RestControllerAdvice(basePackages = "com.pz.gulimall.member.controller")
public class GlobalControllerAdvice {

    @ExceptionHandler(value = MethodArgumentNotValidException.class) //指定扫描的异常
    public R handleValidException(MethodArgumentNotValidException e){
        log.error("数据校验出现问题{}，异常类型：{}",e.getMessage(),e.getClass());
        BindingResult result = e.getBindingResult();
        Map<String,String> res = new HashMap<>();
        result.getFieldErrors().forEach((item)->{
            res.put(item.getField(),item.getDefaultMessage());
        });
        return R.error(BizCodeEnum.VAILD_EXCEPTION.getCode(),BizCodeEnum.VAILD_EXCEPTION.getMsg()).put("data", res);
    }

    //处理所有的异常
    @ExceptionHandler(value = Throwable.class)
    public R handleAllException(Throwable throwable){
        log.error("有未知异常-->{}", throwable.getMessage());
        return R.error(throwable.getMessage());
    }

    //处理自定义异常
    @ExceptionHandler(value = RRException.class)
    public R handleOwnException(RRException throwable){
        return R.error(throwable.getCode(), throwable.getMsg());
    }

    @ExceptionHandler(value = ExecutionException.class)
    public R handleExecutionException(ExecutionException throwable){
        log.error("线程异常异常-->{}", throwable.getMessage());
        return R.error(BizCodeEnum.THREAD_EXCEPTION.getCode(), BizCodeEnum.THREAD_EXCEPTION.getMsg());
    }
}
